package com.rimi.project.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.rimi.project.bean.Book;
import com.rimi.project.dao.BookDao;
import com.rimi.project.util.JDBCutil;

public class BookDaoImpl implements BookDao{

	@Override
	public List<Book> getAllBook() {
		List<Book> books = new ArrayList<>();
		
		String sql = "select * from book_test";
		
		ResultSet resultSet = JDBCutil.preQuery(sql, null);
		
		try {
			while (resultSet.next()) {
				// 取出一本图书
				Book book = new Book(resultSet.getInt("id"), 
						resultSet.getString("book_name"), 
						resultSet.getDouble("price"));
				
				// 将构造图书加入图书列表
				books.add(book);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return books;
	}

	@Override
	public boolean deleteBookById(int id) {
		
		String sql = "delete from book_test where id = ?";
		
		int row = JDBCutil.preUpdate(sql, new String[] {id+""});
		
		return row == 1;
	}

	@Override
	public boolean deleteBookByIds(String[] ids) {
		
		String sql = "delete from book_test where id in (";
		
		// 根据id的个数，拼接?,有多少个id，就拼装多少个？,中间用逗号隔开
		String prefex = "";
		for(int index= 0; index < ids.length; index++) {
			sql += prefex;
			sql += "?";
			prefex = ",";
		}
		
		sql += ")";
		System.out.println(sql);
		
		// 删除
		int row = JDBCutil.preUpdate(sql, ids);
		
		// 比较受影响的行数row 和原有id个数，如果二者不一致
		return row == ids.length;
	}	
}
